<template>
  <a-modal
    v-model:visible="showModal"
    :mask-closable="false"
    title="结算"
    class="limit-modal"
    unmount-on-close
    width="65vw"
    @close="onClose"
    @before-ok="submitFn"
  >
    <a-spin :loading="loading">
      <div class="fee-page">
        <div class="fee-list">
          <div v-for="(item, index) in feeList" :key="index" style="margin: 0 20px">
            <feeitem :fee="item" />
          </div>
          <div class="all-cost">
            <span>合计</span>
            <div class="cost-num">
              <div>应付：{{ feeCostAmount.receiveAmount }}</div>
              <div class="mt-2">待付：{{ feeCostAmount.receivedNotAmount }}</div>
            </div>
          </div>
        </div>

        <a-divider />

        <page-form :model="form" layout="vertical" ref="formRef">
          <page-form-row>
            <page-form-item field="paymentTime" label="结算时间" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
              <i-date-picker class="w-full" v-model="form.paymentTime" show-time value-format="YYYY-MM-DD HH:mm:ss" />
            </page-form-item>
            <page-form-item
              field="paymentWay"
              label="结算方式"
              :rules="{ required: true, message: '请选择' }"
              labelTooltipContent="结算方式支持在系统管理菜单下的【结算方式管理】页面进行配置。"
            >
              <a-select placeholder="请选择" v-model="form.paymentWay" @change="typeChange" popup-container=".fee-page">
                <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
              </a-select>
            </page-form-item>
            <page-form-item
              field="account"
              label="结算账号"
              labelTooltipContent="结算账号支持在系统管理菜单下的【结算方式管理】页面进行配置。"
            >
              <a-select placeholder="请选择" v-model="form.account" :disabled="!form.paymentWay ? true : false" popup-container=".fee-page">
                <a-option
                  v-for="item in accountList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.account + (item.bank ? '_' + item.bank : '')"
                />
              </a-select>
            </page-form-item>
            <page-form-item field="actualAmount" label="结算金额" :rules="{ required: true, message: '请输入' }">
              <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
            </page-form-item>
            <page-form-item field="customerName" label="供应商名称" :rules="{ required: true, message: '请输入供应商名称' }">
              <template #label-extra>
                <i-add-supplier typeText="供应商" :supplierType="supplierTypes" @addOk="addSupplierOk" />
              </template>
              <remote-select
                v-model="form.customerId"
                type="supplier_list"
                :params="{
                  status: 1,
                  idList: [form.customerId],
                  supplierTypesAnd: supplierTypes,
                  refreshSupplierSelect,
                }"
                @change="customerNameChange"
              />
            </page-form-item>
            <page-form-item field="customerAccount" label="供应商收款账号">
              <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
            </page-form-item>
            <page-form-item field="settlementRemark" label="结算备注" size="2/3">
              <i-input textarea placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
            </page-form-item>
            <page-form-item label="结算凭证（支持上传jpg、png格式，最多上传10张）" size="1">
              <upload-img v-model="form.fileIdList" :limit="10" />
            </page-form-item>
          </page-form-row>
        </page-form>
      </div>
    </a-spin>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup name="CarMaintenanceConfirmFees">
  // 【结算】保养、维修、年检
  import feeitem from './comfirm-fee-item.vue'
  import { Message } from '@arco-design/web-vue'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/sOrder'
  import { getConfirmDetails, confirmOrderFee } from '@/api/finance/costConfirm'
  import { ref } from 'vue'

  const paywayEnum = ref([]) //收付款方式
  const accountList = ref([]) //收付款账号列表
  const feeCostAmount = ref({}) //收付款类型及金额
  const formRef = ref(null)
  const okLoading = ref(false)
  const form = ref({
    idList: [], //结算单ids
  })
  // 打开弹窗
  const showModal = ref(false)
  const show = (idList) => {
    showModal.value = true
    if (idList) {
      getFeeList(idList)
    }
  }
  const onClose = () => {
    showModal.value = false
    // 重置
    resetData()
  }
  const resetData = () => {
    paywayEnum.value = []
    accountList.value = []
    supplierList.value = []
    form.value = {}
    feeList.value = []
  }
  // 获取费项
  const loading = ref(false)
  const costType = ref(null) // type  0-收款，1-付款
  const costName = ref('')
  const getFeeList = (ids) => {
    loading.value = true
    getConfirmDetails({ idList: ids })
      .then((res) => {
        feeCostAmount.value = {
          receiveAmount: unitVal(Math.abs(res.result.receiveAmount), '元'),
          receivedNotAmount: unitVal(Math.abs(res.result.receivedNotAmount), '元'),
        }
        // 初始化form
        initFormData(ids, res.result.carAssetFeeList[0], Math.abs(res.result.receivedNotAmount))
        // 初始化费项
        initFeeList(res.result.carAssetFeeList)
        // 获取收付款方式
        getTypeList(res.result.costType)
      })
      .finally(() => {
        loading.value = false
      })
  }

  // 初始化费用列表
  const feeList = ref([]) // 收付款列表
  const initFeeList = (list) => {
    feeList.value = list
    // 获取供应商
    if (list && list.length) {
      processSupplierTypes(list)
    }
  }
  const initFormData = (ids, fee, actualAmount) => {
    costType.value = fee.costType
    costName.value = '付款'
    form.value = {
      idList: ids,
      paymentTime: fee.createTime,
      actualAmount: actualAmount,
      // 默认供应商
      customerId: fee.supplierId,
      customerName: fee.supplierName,
      customerType: 1,
      customerAccount: undefined,
      settlementRemark: undefined,
      paymentWay: undefined,
      account: undefined,
    }
  }

  // 收付款类型
  const getTypeList = (costType) => {
    getAccountByPageData({ type: costType == 0 ? 0 : 1 }).then((res) => {
      // 过滤
      var data = res.result
      data.forEach((i) => {
        if (i.way != '1' && i.way != '2' && i.way != '3' && i.way != '4' && i.way != '5') {
          paywayEnum.value.push(i)
        }
      })
    })
  }
  // 账号
  const typeChange = (e) => {
    if (e) {
      form.value.account = ''
    }
    paywayEnum.value.forEach((el) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: costType.value == 0 ? 0 : 1 }).then((res) => {
          accountList.value = res.result
        })
      }
    })
  }
  // 修理厂选择
  const supplierList = ref([])
  const supplierTypes = ref([])
  // 封装一个函数以提高可复用性和可维护性
  function processSupplierTypes(list) {
    const feeCategoryList = list.map((i) => i.feeCategory)
    // 定义映射表，简化逻辑
    const mapping = {
      1: 1,
      2: 0,
      default: 6,
    }
    // 转换逻辑
    let changeTypes = feeCategoryList.map((i) => {
      return mapping[i] ?? mapping.default // 使用默认值处理未知键
    })
    // 去重并更新 supplierTypes
    supplierTypes.value = [...new Set(changeTypes)]
  }
  // 获取供应少列表
  const refreshSupplierSelect = ref(0)
  const addSupplierOk = () => {
    refreshSupplierSelect.value++
  }
  const customerNameChange = (e, option = {}) => {
    form.value.customerName = option.supplierName
    form.value.customerId = option.id
  }
  const emit = defineEmits(['ok'])
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        const param = {
          ...form.value,
        }
        confirmOrderFee(param)
          .then((res) => {
            okLoading.value = false
            Message.success(res.message)
            showModal.value = false
            emit('ok')
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }
  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  .fee-list {
    padding-top: 20px;
    border: 1px solid #f2f3f5;
  }
  .all-cost {
    font-weight: 600;
    padding: 12px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    .cost-num {
      color: #1890ff;
    }
  }
  // 弹窗添加的样式
  .fee-page {
    width: 100%;
    max-height: 70vh;
    position: relative;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
</style>
